<?php
	if(isset($_COOKIE['session_id']) && isset($_COOKIE['user_id']) && isset($_POST['comment']) && isset($_POST['topic'])){
		$hash = addslashes($_COOKIE['session_id']);
		$uid = addslashes($_COOKIE['user_id']);

		include('config.php');
		
		$query = 'SELECT U.username FROM USERS U WHERE user_id = '. $uid . ' AND password = \'' . $hash . '\'';		
		$login_results = mysql_query($query);
	
		if(mysql_num_rows($login_results) >= 1){
			$comment = htmlentities(addslashes($_POST['comment']));
			$topic = htmlentities(addslashes($_POST['topic']));

			if($comment == '' || $topic == ''){
				header('Location: index.php');
			}
			
			$tid = mt_rand(10000000, 99999999);
				
			$query = 'SELECT U.thread_id FROM THREADS U WHERE thread_id = \'' . $tid . '\'';
			$results = mysql_query($query);
		
			while(mysql_num_rows($results) >= 1){
				$tid = mt_rand(10000000, 99999999);
			
				$query = 'SELECT U.thread_id FROM THREADS U WHERE thread_id = \'' . $tid . '\'';
				$results = mysql_query($query);
			}
				
			$row = mysql_fetch_array($login_results);
			$query = 'INSERT INTO THREADS VALUES (' . $tid . ',  \'' . $row['username'] . '\', 1, NOW( ) , \'' . $topic . '\')';
			mysql_query($query);
			
			$query = 'INSERT INTO COMMENTS VALUES(' . $tid . ', ' . $uid . ', NOW( ), \'' . $comment . '\')';
			mysql_query($query);
			
			mysql_close($mysql_handle);
			header('Location: index.php?page=threads&id=' . $tid);		
		}else{
			mysql_close($mysql_handle);
			
			header('Location: index.php');
		}
	}else{
		header('Location: index.php');
	}
?>